package com.lanju.service.impl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.lanju.common.WxMessageUtil;
import com.lanju.dao.HouseEntrustDao;
import com.lanju.dao.SMSCaptchaDao;
import com.lanju.dao.UserDao;
import com.lanju.entity.Entrust;
import com.lanju.entity.User;
import com.lanju.model.ResultModel;
import com.lanju.service.HouseEntrustService;


@Service
public class HouseEntrustServiceImpl implements HouseEntrustService{

    private static final Logger LOGGER = LoggerFactory.getLogger(HouseEntrustServiceImpl.class);
    
    @Autowired
    HouseEntrustDao entrustDao;
    
    @Autowired
    SMSCaptchaDao sMSCaptchaDao;
    
    @Autowired
    UserDao userDao;

    /** 新增 */
    @Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
    public ResultModel add(Entrust entrust,HttpServletRequest request,HttpServletResponse response) {
        try {
        	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        	entrust.setStatus("0");
        	entrustDao.persist(entrust);
        	Entrust en=entrustDao.getById(entrust.getHouseId());
        	//发送微信消息
        	Map<String,Object> map =new HashMap<>();
        	map.put("reviceType", "业主委托提醒");
    		List<User> ulist=userDao.getSendMessageUser(map);
    		String templateId  ="BdS48KfltsbkhCyNQJ3dZKt1MW6-jzslwhxM1DbzaP4";
    		Integer count=0;
    		if(ulist != null && ulist.size()>0){
    			for(int i=0;i<ulist.size();i++){
    				User u_=ulist.get(i);
    				if(!StringUtils.isEmpty(u_.getOpenId())){
    					String data="{\"touser\":\""+u_.getOpenId()+"\",\"template_id\":\""+templateId+"\",\"topcolor\":\"#FF0000\", "
    							+ "\"data\":{\"first\": { \"value\":\""+"业主委托房源提醒"+"\",\"color\":\"#173177\"},"
    									+ "\"keyword1\":{\"value\":\""+entrust.getAddress()+"\",\"color\":\"#173177\" },"
    											+ "\"keyword2\": { \"value\":\""+entrust.getNickName()+"\",\"color\":\"#173177\"},"
    													+ "\"keyword3\":{\"value\":\""+entrust.getPhone()+"\",\"color\":\"#173177\"}, "
    													+ "\"keyword4\":{\"value\":\""+sdf.format(entrust.getCreateTime())+"\",\"color\":\"#173177\"}, "
    															+ "\"remark\":{\"value\":\""+"您有一份业主委托房源提醒,请尽快处理"+"\",\"color\":\"#173177\"}"
    																	+ "}}";
    					synchronized (data) {
    						WxMessageUtil.sendcontractPayMessage(request, response, data);
    						count ++;
    					}
    				}	
    			}
    		}

    		System.out.println("总共发送给"+count+"个管理员");
            return ResultModel.success("录入成功", en);
        } catch (Exception e) {
            LOGGER.error("addEntrust fail",e);
        }
        return ResultModel.fail("录入失败", null);
    }

    /** 根据id删除 */
    @Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
    public ResultModel del(Entrust entrust) {
    	String entrustId = entrust.getHouseId();
        Entrust obj = entrustDao.getById(entrustId);
        if(obj==null){
            return ResultModel.fail("Entrust不存在", null);
        }
        try {
            entrustDao.remove(entrust);;
            return ResultModel.success("删除成功", null);
        } catch (Exception e) {
            LOGGER.error("delEntrust fail",e);
        }
        return ResultModel.fail("删除失败", null);
    }
    
    /** 根据id修改 */
    @Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
    public ResultModel edit(Entrust entrust) {
        Entrust obj = entrustDao.getById(entrust.getHouseId());
        if(obj==null){
            return ResultModel.fail("Entrust不存在", null);
        }
        try {
        	obj.setStatus(entrust.getStatus());
            entrustDao.merge(obj);
            return ResultModel.success("编辑成功", null);
        } catch (Exception e) {
            LOGGER.error("editEntrust fail",e);
        }
        return ResultModel.fail("编辑失败", null);
    }

    /** 根据id获取 */
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
    public Entrust getById(String id) {
        Entrust obj = entrustDao.getById(id);
        return obj;
    }
    
    /** 根据参数获取 */
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
    public Entrust getByParam(Entrust entrust) {
        Entrust obj = entrustDao.getByParam(entrust);
        return obj;
    }
    
    

    /** 分页查询 */
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
    public Map<String, Object> getList(Map param, int pageSize, int offset) {
    	 Map<String, Object> rsMap = new HashMap<String, Object>();
    	 long count = entrustDao.getListCount(param);
         List<Entrust> list = entrustDao.getList(param, pageSize, offset);
         rsMap.put("total", count);
         rsMap.put("rows", list);
        return rsMap;
    }

	@Override
	@Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
	public Map<String, Object> updateEntrustType(Entrust entrust) {
		 Map<String, Object> result =  new HashMap<String, Object>();
		try {
			result = new HashMap<String, Object>();
			 Entrust en= entrustDao.merge(entrust);
			 result.put("success", true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	@Override
	@Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
	public ResultModel editHouseEntrust(Entrust entrust) {
	        try {
	            entrustDao.update(entrust);
	            return ResultModel.success("编辑成功", null);
	        } catch (Exception e) {
	            LOGGER.error("editEntrust fail",e);
	        }
	        return ResultModel.fail("编辑失败", null);
	}
    
  
}
